const svg = d3.select(".trend-svg");
const margin = { top: 0, right: 0, bottom: 0, left: 0 };
const width = +svg.attr("width") - margin.left - margin.right;
const height = +svg.attr("height") - margin.top - margin.bottom;
const rectBg = d3.select('.rect-bg');
const rippler = d3.select('.ripple-wrap');
const pathWrap = d3.select('.path-wrap');
const tooltip = d3.select('.tooltip');
const tableWrap = d3.select('.trend-table');
const dateLabel = d3.select('.date-type');
const gx = svg.select(".x-scale");
const gy = svg.select(".y-scale");
let xAxis;
let yAxis;
let xScale;
let yScale;

const xMap = function (d, i) {
  const range = d3.interpolateNumber(0, 968);
  return range(i / 11) + 188;
};

// 鼠标悬浮点
let curSelect;

// 趋势图点数据
let data;
let dataSource;

// 参数筛选
// let trader = 'buyer';
// let areas = ['sichuan2'];
let timeDensity = 'day';
const dateNow = new Date();
let end = dateNow.toLocaleDateString();
let start = new Date(new Date(end).getTime() - 11 * 3600 * 24 * 1000).toLocaleDateString();

let selectType = '';
// let selectYear = dateNow.getFullYear();
// let selectMonth = dateNow.getMonth() + 1;
// let selectDay = dateNow.getDate();

let selectYear;
let selectMonth;
let selectDay;

svg.on('mousemove', function () {
  if (!data || data.length === 0) return;
  const { offsetX, offsetY } = d3.event;
  const idx = Math.ceil((offsetX - 144) / 88);
  if (idx < 1 || idx > 12 || curSelect === idx) return;
  const datum = data[idx - 1];

  // todo
  let ds = dataSource[idx - 1];
  let text;
  if (timeDensity === 'year') {
    text = dateFormater(ds.date, 'YY', 'zh');
  } else if (timeDensity === 'month') {
    text = dateFormater(ds.date, 'M', 'zh');
  } else if (timeDensity === 'day') {
    text = dateFormater(ds.date, 'D', 'zh');
  }


  $('.ratio-wrap .rect').show(200);
  $('.ratio-label .label').show(200);
  $('.ratio-wrap .rect').eq(idx - 1).hide(200);
  $('.ratio-label .label').eq(idx - 1).hide(200);

  const x = xMap(datum, idx);
  const y = yScale(datum);
  tooltip.select('.ratio').text(`1元=${datum}万金`);
  tooltip.select('.label span').text(text);
  tooltip
    .transition()
    .duration(600)
    .ease(d3.easePolyOut)
    .style('top', `${y - 50}px`)
    .style('left', `${x - 160}px`)
    .style('opacity', 1);

  rectBg
    .transition()
    .duration(200)
    .ease(d3.easePolyOut)
    .style('opacity', 1)
    .attr('x', x - 176);

  rippler
    .attr('class', 'ripple-wrap')
    .transition()
    .delay(1)
    .style('top', `${y + 28}px`)
    .style('left', `${x - 110}px`)


  setTimeout(function () {
    rippler.attr('class', 'ripple-wrap show');
  }, 300);

  curSelect = idx;
});


function customXAxis(g) {
  g.call(xAxis);
  g.select(".domain").remove();
  g.selectAll(".tick line").remove();
  g.selectAll(".tick text").attr("dy", 20);
}

function customYAxis(g) {
  g.call(yAxis);
  g.select(".domain").remove();
  g.selectAll(".tick line").remove();
  g.selectAll(".tick text").attr("x", -20).attr("dy", 2);
}

function getYDomain() {
  let min = Math.floor(d3.min(data));
  let max = Math.ceil(d3.max(data));
  const modular = (max - min) % 4;
  if (modular > 0) {
    max += 4 - modular;
  } 

  // if (min % 2 > 0) {
  //   min -= 1;
  //   max += 3;
  // }

  // console.log(min, max)
  return [min, max];
}

function formatTick(d) {
  if (timeDensity === 'year') {
    return dateFormater(d, 'YY', 'zh');
  } else if (timeDensity === 'month') {
    return dateFormater(d, 'M', 'zh');
  } else if (timeDensity === 'day') {
    return dateFormater(d, 'D', 'zh');
  }
}

function setScales() {
  xScale = d3.scaleTime()
    .domain([new Date(start), new Date(end)])
    .range([0, 968]);

    getYDomain();
  yScale = d3.scaleLinear()
    .domain(getYDomain())
    .range([320, 20]);

  xAxis = d3.axisBottom(xScale)
    .tickFormat(formatTick);

  yAxis = d3.axisRight(yScale)
    .ticks(4)
    .tickFormat(function (d) {
      return `${d}万金`
    });

  gx.attr("transform", "translate(188, 360)")
    .call(customXAxis);

  gy.attr("transform", "translate(60, 0)")
    .call(customYAxis);
}

// 渲染走势图
function renderPath() {
  pathWrap.selectAll('g').remove();
  pathWrap.selectAll('.wave').remove();

  pathWrap.append('g')
    .attr('class', 'liner')
    .selectAll('.line')
    .data(data)
    .enter()
    .append('line')
    .attr("class", (d, i) => `line line${i}`)
    .attr('stroke', '#d7d7d7')
    .attr('stroke-width', '1')
    .attr('x1', xMap)
    .attr('y1', 0)
    .attr('x2', xMap)
    .attr('y2', 360);

  pathWrap.append('path')
    .datum(data)
    .attr('class', 'wave')
    .style('stroke', '#3399fe')
    .attr('stroke-width', '5')
    .attr(
      'd',
      d3.line()
        .curve(d3.curveCatmullRom)
        .x(function (d, i) {
          const range = d3.interpolateNumber(0, 968);
          return range(i / 11) + 188;
        })
        .y(d => yScale(d))
    );

  pathWrap.append('g')
    .attr('class', 'scatter')
    .attr('fill', '#fff')
    .selectAll('.dot')
    .data(data)
    .enter()
    .append('circle')
    .attr("class", (d, i) => `dot dot${i}`)
    .attr('filter', 'url(#dropShadow)')
    .attr('r', 10)
    .attr('cx', xMap)
    .attr('cy', d => yScale(d))

  pathWrap.append('g')
    .attr('class', 'ratio-label')
    .attr('fill', '#333')
    .selectAll('.label')
    .data(data)
    .enter()
    .append('text')
    .attr("class", (d, i) => `label label${i}`)
    .attr('text-anchor', 'middle')
    .text(d => d)
    .attr('x', xMap)
    .attr('y', d => yScale(d) - 20)

  pathWrap.append('g')
    .attr('class', 'ratio-wrap')
    .attr('fill', '#333')
    .selectAll('.rect')
    .data(data)
    .enter()
    .append('rect')
    .attr("class", (d, i) => `rect rect${i}`)
    .attr('width', '44')
    .attr('height', '16')
    .attr('rx', '8')
    .attr('ry', '8')
    .attr('x', (d, i) => {
      const range = d3.interpolateNumber(0, 968);
      return range(i / 11) + 188 - 22;
    })
    .attr('y', d => yScale(d) - 33)

}


// 渲染表格
function renderTable(data) {
  tableWrap.select('.tt-content').remove();
  if (data.length === 0) {
    $('.trend-table').append(`
      <div class="tt-content no-item">暂无此时段数据，请重新筛选</div>
    `)
    return;
  }
  data = [...data].reverse();
  tableWrap.append('div')
    .attr('class', 'tt-content')
    .selectAll('.tt-row')
    .data(data)
    .enter()
    .append('ul')
    .attr('class', 'tt-row')
    .html(d => `
          <li>${formatTableDate(d.date)}</li>
          <li>${d.area}</li>
          <li>游戏币比例</li>
          <li>1元=${d.ratio}万金</li>
        `)
}

function formatTableDate(date) {
  const dateArr = date.split(/[/.-]/);
  if (timeDensity === 'year') {
    return `${dateArr[0]}年`;
  } else if (timeDensity === 'month') {
    return `${dateArr[0]}年${dateArr[1]}月`;
  } else if (timeDensity === 'day') {
    return `${dateArr[0]}年${dateArr[1]}月${dateArr[2]}日`;
  }
}

function getData() {
  tooltip.style('opacity', 0);
  rectBg.style('opacity', 0)
  rippler.attr('class', 'ripple-wrap');

  if (selectType) {
    $('.search-notice').text(`当前筛选：${formatTableDate(start)} - ${formatTableDate(end)}`);
  }
  
  
  $.ajax({
    url: 'http://192.168.0.110:3000/api/DNFHistories/trended',
    data: {
      trader,
      areas,
      timeDensity,
      start,
      end
    },
    success: function (res) {
      if (res.error) {
        return alert('数据出错');
      }
      // console.log(res.data);

      dataSource = res.data.map(d => {
        const { area, date, ratio } = d;
        // console.log(new Date(date))
        return {
          date: new Date(date).toLocaleDateString(),
          area,
          ratio: ratio.toFixed(2),
        }
      });
      renderTable(dataSource);

      data = res.data.map(d => parseFloat(d.ratio.toFixed(2)));
      setScales();
      renderPath();
    }
  });

}

// 获取数据
getData();


// 选择日期
$('.select-type').click(function(e) {
  e.stopPropagation();
  $('.st-dropdown').toggleClass('show');

  $(document.body).on('click', clickOutside);
});

$('.select-type li').click(function(e) {
  e.stopPropagation();
  const text = $(this).text();
  if (text === selectType) return;
  selectType = text;
  $('.select-type').addClass('selected');
  $('.st-dropdown').removeClass('show');
  $('.date-wrap').addClass('show');
  $('.select-type span').text(text);
  if (text === '按年查看') {
    timeDensity = 'year';
    this.selectMonth = '';
  } else if (text === '按月查看') {
    timeDensity = 'month';
    this.selectDay = '';
  } else if (text === '按日查看') {
    timeDensity = 'day';
  }
});

$('.date-wrap').click(function(e) {
  e.stopPropagation();
  if (selectType === '按月查看') {
    if (selectYear) $('.month-wrap').addClass('show');
  } else if (selectType === '按日查看') {
    if (selectYear && selectMonth) {
      $('.day-wrap .head .text').text(`${selectYear}年${selectMonth}月`);
      if (!$('.days').text()) renderDays(selectYear, selectMonth);
      $('.day-wrap').addClass('show');
    }
  }
  $('.picker').addClass('show');
  $(document.body).on('click', clickOutside);
})

years.forEach(year => {
  $('.years').append(`
    <li><span class="${year === selectYear ? 'active' : ''}">${year}</span></li>
  `);
});

// 年份点击
$('.years li').click(function(e) {
  e.stopPropagation();
  selectYear = parseInt($(this).text());
  setActiveYear();
  if (timeDensity === 'year') {
    start = `${selectYear - 11}`;
    end = `${selectYear}`;
    $('.date-wrap > span').text(`${end}年`);
    dateLabel.text('年');
    getData();
    clickOutside();
  } else {
    $('.month-wrap .head .text').text(`${selectYear}年`)
    $('.month-wrap').addClass('show');
  }
});


// 月份点击
$('.months li').click(function(e) {
  e.stopPropagation();
  selectMonth = parseInt($(this).text());
  setActiveMonth();
  if (timeDensity === 'month') {
    if (selectMonth === 12) {
      start = `${selectYear}/1`;
    } else {
      start = `${selectYear - 1}/${selectMonth + 1}`;
    }
    end = `${selectYear}/${selectMonth}`;
    $('.date-wrap > span').text(`${selectYear}年${selectMonth}月`);
    dateLabel.text('月');
    getData();
    clickOutside();
  } else if (timeDensity === 'day') {
    $('.day-wrap .head .text').text(`${selectYear}年${selectMonth}月`);
    renderDays();
    $('.day-wrap').addClass('show');
  }
});

$('.month-wrap .text-wrap').click(function(e) {
  e.stopPropagation();
  $('.month-wrap').removeClass('show');
});

function renderDays() {
  const days = getDays(selectYear, selectMonth);
  $('.days').html('');
  days.forEach(day => {
    $('.days').append(`
      <li><span>${day}</span></li>
    `);
  });
  $('.days li').click(dayClick);
}

// 日点击
function dayClick(e) {
  e.stopPropagation();
  selectDay = parseInt($(this).text());
  d3.selectAll('.days li').select('span').attr('class', '');
  $(this).find('span').addClass('active');
  if (timeDensity === 'day') {
    end = `${selectYear}/${selectMonth}/${selectDay}`;
    start = new Date(new Date(end).getTime() - 11 * 3600 * 24 * 1000).toLocaleDateString();
    dateLabel.text('日');
    $('.date-wrap > span').text(`${selectYear}年${selectMonth}月${selectDay}日`);
    getData();
    clickOutside();
  }
}

$('.day-wrap .text-wrap').click(function(e) {
  e.stopPropagation();
  $('.month-wrap').addClass('show');
  $('.day-wrap').removeClass('show');
});

function clickOutside() {
  $(document.body).off('click', clickOutside);
  $('.picker').removeClass('show');
  $('.month-wrap').removeClass('show');
  $('.day-wrap').removeClass('show');
  $('.st-dropdown').removeClass('show');
}

// 收起
$('.trend-wrap .trend-toggle').click(function() {
  $('.trend-wrap').addClass('extract');

});

$('.trend-table .trend-toggle').click(function() {
  $('.trend-wrap').removeClass('extract');
});

// 日期前后翻页
$('.arrow-wrap').click(function() {
  const el = $(this);
  if (el.hasClass('yb')) {
    selectYear -= 1;
    $('.month-wrap .head .text').text(`${selectYear}年`);
    setActiveYear();
  } else if (el.hasClass('yf')) {
    if (selectYear === curYear) return;
    selectYear += 1;
    $('.month-wrap .head .text').text(`${selectYear}年`);
    setActiveYear();
  } else if (el.hasClass('mb')) {
    if (selectMonth === 1) {
      selectYear -= 1;
      setActiveYear();
      selectMonth = 12;
    } else {
      selectMonth -= 1;
    }
    setActiveMonth();
    renderDays();
    $('.day-wrap .head .text').text(`${selectYear}年${selectMonth}月`);
  } else if (el.hasClass('mf')) {
    if (selectYear === curYear && selectMonth === 12) return;
    if (selectMonth === 12) {
      selectYear += 1;
      setActiveYear();
      selectMonth = 1;
    } else {
      selectMonth += 1;
    }
    setActiveMonth();
    renderDays();
    $('.day-wrap .head .text').text(`${selectYear}年${selectMonth}月`);
  }
});

function setActiveYear() {
  $('.years li').each(function(idx, el) {
    const span = $(el).find('span');
    if (span.text() == selectYear) {
      span.addClass('active');
    } else {
      span.removeClass('active');
    }
  })
}

function setActiveMonth() {
  $('.months li').each(function(idx, el) {
    const span = $(el).find('span');
    if (parseInt(span.text()) == selectMonth) {
      span.addClass('active');
    } else {
      span.removeClass('active');
    }
  })
}

$('.search-btn').click(function() {
  getData();
});